<!--
 * @Description: 预约单查询
 * @Autor: 何兴家
 * @Date: 2020-11-30 10:50:32
 * @LastEditors: 马毅
 * @LastEditTime: 2021-06-24 14:41:04
-->
<template>
  <div>
    <TopFilter ref="topFilter" :cols="4" :labelWidth="100" :list="topFilterList" @filterChange="handleSearch" @onCollapse="collapseHandle"></TopFilter>
    <FilterTable
      ref="table"
      columnsRef="tempRef"
      :columns="columns"
      :fetchapi="fetchapi"
      :params="fetchParams"
      :datakey="'rows'"
      selectionType="single"
      :onRowSelectChange="handleTableSelectChange"
      :onSyncTableData="handleSyncTableData"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <template slot="controls">
        <AjaxButton v-if="appId == 'beijing'" size="small" type="primary" :click="handleCancelBtnClick">取消预约</AjaxButton>
        <el-button size="small" type="primary" @click="handleRemindRecordClick">提醒记录</el-button>
        <AjaxButton size="small" type="primary" :click="handleDerive">导出</AjaxButton>
      </template>
    </FilterTable>

    <!-- 编辑/查看预约单 -->
    <BaseDialog
      :visible.sync="showDetailPanel"
      :title="bookingOrderPageType == 'edit' ? '编辑' : '查看' + '预约单'"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <precontractArrange :defaultPageType="bookingOrderPageType" :defaultBookingOrderNo="bookingOrderPageData.bookingOrderNo" @close="showDetailPanel = false" @refesh="refeshTableData" />
    </BaseDialog>

    <!-- 取消预约 -->
    <BaseDialog :visible.sync="showCancelPanel" title="取消预约" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <cancelBookingOrder @close="showCancelPanel = false" @refesh="refeshTableData" :bookingOrderNo="selectedBookingNo" />
    </BaseDialog>

    <!-- 提醒记录 -->
    <BaseDialog :visible.sync="showRemindRecordPanel" title="提醒记录" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <remindRecord @close="showRemindRecordPanel = false" :bookingOrderDetail="selectedTableData[0]" />
    </BaseDialog>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { confirmAction, findFormItem, findTableItem, notifyActio0, exportExcelFile } from '@/utils';
import dictCode from '@/utils/dictCode';
import { getAppId } from '@/assets/js/auth';

import precontractArrange from '../precontractArrange';
import cancelBookingOrder from './cancelBookingOrder';
import remindRecord from './remindRecord';

import { searchRoleByCode, searchRoleByCodes } from '@/api/common/empSelect/index';
import { queryPrecontractOrder, precontractOrderExport } from '@/api/repair/repairReception/precontractStatus';

export default {
  mixins: [dictionary],
  components: { precontractArrange, cancelBookingOrder, remindRecord },
  data() {
    this.bookingOrderPageType = null;
    this.bookingOrderPageData = {};
    return {
      appId: getAppId(),
      topFilterList: this.createTopFIlterList(),
      columns: this.createTableColumns(),
      fetchapi: queryPrecontractOrder,
      fetchParams: {},
      syncTableData: [], // 同步的table数据
      selectedTableData: [], // 选中的table数据
      showDetailPanel: false, // 是否显示详情编辑弹窗
      showCancelPanel: false, // 是否显示取消弹窗
      showRemindRecordPanel: false // 是否显示提醒记录弹窗
    };
  },
  computed: {
    selectedBookingNo() {
      return this.selectedTableData.length ? this.selectedTableData[0].bookingOrderNo : '';
    }
  },
  mounted() {
    this.queryServiceAdviserList();
    this.queryRepairTechnician();
  },
  methods: {
    createTopFIlterList() {
      return [
        {
          type: 'INPUT',
          label: '预约单号',
          fieldName: 'bookingOrderNo'
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license'
        },
        {
          type: 'SELECT',
          label: '预约单状态',
          fieldName: 'bookingOrderStatus',
          itemList: this.createDictList(8067)
        },
        {
          type: 'SELECT',
          label: '进厂状态',
          fieldName: 'comeStatus',
          itemList: this.createDictList(8084)
        },
        {
          type: 'SELECT',
          label: '离预约进厂时间',
          fieldName: 'arrivalComeTime',
          placeholder: '请选择',
          itemList: [
            { text: '15分钟', value: 15 },
            { text: '30分钟', value: 30 },
            { text: '1小时', value: 60 },
            { text: '24小时', value: 1440 },
            { text: '72小时', value: 4320 }
          ]
        },
        {
          type: 'SELECT',
          label: '服务顾问',
          fieldName: 'serviceAdvisor',
          itemList: []
        },
        // {
        //   type: 'SELECT',
        //   label: '预约来源',
        //   fieldName: 'bookingSource',
        //   itemList: this.createDictList('8010')
        // },
        // {
        //   type: 'SELECT',
        //   label: '是否确认',
        //   fieldName: 'isConfirm',
        //   itemList: this.createDictList('1004')
        // },
        {
          type: 'RANGE_DATE',
          label: '预约进厂时间',
          fieldName: 'bookingComeTimeBegin|bookingComeTimeEnd',
          placeholder: '请选择预约进厂时间',
          valueFormat: 'yyyy-MM-dd'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'table_actions',
          render: props => {
            return (
              <div>
                <el-button
                  size="mini"
                  type="text"
                  disabled={props.row.bookingOrderStatus != '80671001'}
                  onClick={() => {
                    this.handleEdit(props.row);
                  }}
                >
                  编辑
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  onClick={() => {
                    this.handleCheckout(props.row);
                  }}
                >
                  明细
                </el-button>
              </div>
            );
          }
        },
        {
          title: '工单号',
          dataIndex: 'roNo',
          showOverflowTooltip: true,
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '开单日期',
          dataIndex: 'roCreateDate',
          showOverflowTooltip: true,
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '服务顾问', // 开单
          dataIndex: 'serviceAdvisor',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          dictItems: []
        },
        {
          title: '预约单号',
          dataIndex: 'bookingOrderNo',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '预约顾问',
          dataIndex: 'bookServiceAdvisor',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          dictItems: []
        },
        {
          title: '车牌号',
          dataIndex: 'license',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '预约来源',
          dataIndex: 'bookingSource',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8010'),
          dictItems: this.createDictList('8010')
        },
        // {
        //   title: '是否确认',
        //   dataIndex: 'isConfirm',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: [
        //     { text: '已确认', value: 10041001 },
        //     { text: '未确认', value: 10041002 }
        //   ],
        //   dictItems: [
        //     { text: '已确认', value: 10041001 },
        //     { text: '未确认', value: 10041002 }
        //   ]
        // },
        {
          title: '预约类别',
          dataIndex: 'bookingTypeCode',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8055').map(item => ({ text: item.text, value: item.value + '' })),
          dictItems: this.createDictList('8055').map(item => ({ text: item.text, value: item.value + '' }))
        },
        {
          title: '接受预约日',
          dataIndex: 'createdAt',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'date-range',
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '预约进厂时间',
          dataIndex: 'bookingComeTime',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'date-range',
          dateFormat: 'yyyy-MM-dd HH:mm'
        },
        {
          title: '车主',
          dataIndex: 'ownerName',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '联系人',
          dataIndex: 'contactorName',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '联系人电话',
          dataIndex: 'contactorPhone',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '联系人手机',
          dataIndex: 'contactorMobile',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '预约单状态',
          dataIndex: 'bookingOrderStatus',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8067'),
          dictItems: this.createDictList('8067')
        },
        {
          title: '进厂状态',
          dataIndex: 'comeStatus',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8084'),
          dictItems: this.createDictList('8084')
        },
        {
          title: '指定技师',
          dataIndex: 'chiefTechnician',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          dictItems: []
        },
        {
          title: '取消预约发起',
          dataIndex: 'canclePerson',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [
            { text: '客户', value: '客户' },
            { text: '经销商', value: '经销商' }
          ]
        },
        {
          title: '取消预约原因',
          dataIndex: 'cancleReason',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8066'),
          dictItems: this.createDictList('8066')
        },
        {
          title: '备注',
          dataIndex: 'remark',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.$refs.table.EXECUTE_RESET_HEIGHT();
      });
    },
    // 获取服务顾问列表
    async queryServiceAdviserList() {
      let serviceConsultant = { role: dictCode.SERVICE_CONSULTANT };
      let res = await searchRoleByCode(serviceConsultant);
      if (res.resultCode == 200) {
        let serviceAdviserDict = res.data.map(item => ({ text: item.employeeName, value: item.userId + '' }));
        findFormItem(this.topFilterList, 'serviceAdvisor').itemList = serviceAdviserDict;
        let tableColumns = [findTableItem(this.columns, 'serviceAdvisor'), findTableItem(this.columns, 'bookServiceAdvisor')];
        tableColumns.forEach(item => {
          item.filterItems = item.dictItems = serviceAdviserDict;
        });
      }
    },
    // 查询维修技师列表
    async queryRepairTechnician() {
      let technician = { role: dictCode.TECHNICIAN };
      let res = await searchRoleByCodes(technician);
      if (res.resultCode == 200) {
        let tableTarget = findTableItem(this.columns, 'chiefTechnician');
        tableTarget.dictItems = tableTarget.filterItems = res.data.map(item => ({ text: item.employeeName, value: item.userId + '' }));
      }
    },
    // 点击搜索
    handleSearch(val) {
      val && val.bookingComeTimeEnd && (val.bookingComeTimeEnd = val.bookingComeTimeEnd.split(' ')[0] + ' 23:59:59');
      this.fetchParams = Object.assign({}, this.fetchParams, val);
    },
    // 同步table数据
    handleSyncTableData(list) {
      this.syncTableData = list;
    },
    // 刷新table数据
    refeshTableData() {
      this.fetchParams = { ...this.fetchParams };
    },
    // table选中变化
    handleTableSelectChange(list) {
      this.selectedTableData = list;
    },
    // 点击行项编辑
    handleEdit(row) {
      console.log(row, '行项');
      this.bookingOrderPageType = 'edit';
      this.bookingOrderPageData = row;
      this.showDetailPanel = true;
    },
    // 点击行项明细
    handleCheckout(row) {
      console.log(row, '行项');
      this.bookingOrderPageType = 'detail';
      this.bookingOrderPageData = row;
      this.showDetailPanel = true;
    },
    // 点击取消预约
    async handleCancelBtnClick() {
      if (!this.selectedTableData.length) return notifyAction('请选择需要取消预约的行项', 'warning');
      this.showCancelPanel = true;
    },
    // 点击提醒记录
    handleRemindRecordClick() {
      if (!this.selectedTableData.length) return notifyAction('请选择需要查看的行项', 'warning');
      this.showRemindRecordPanel = true;
    },
    // 点击导出
    async handleDerive() {
      let formParams = this.$refs.topFilter.GET_FORM_DATA();
      if (formParams[0]) return;
      let res = await precontractOrderExport(formParams[1]);
      exportExcelFile(res.data, '预约单导出');
    }
  }
};
</script>

<style scoped></style>
